package cn.group7.padserver.controller;

import cn.group7.padserver.common.Flag;
import cn.group7.padserver.controller.responseformat.Code;
import cn.group7.padserver.controller.responseformat.Result;
import cn.group7.padserver.entity.Page;
import cn.group7.padserver.pojo.Expert;
import cn.group7.padserver.pojo.Question;
import cn.group7.padserver.service.ExpertService;
import cn.group7.padserver.service.QuestionService;
import io.swagger.annotations.ApiOperation;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author 谷汉斌
 * @description 问答控制器
 * @createTime 2024/8/3 下午3:57
 */
@Slf4j
@RestController
@RequestMapping("/questions")
public class QuestionController {

    @Resource
    private QuestionService questionService;

    @Resource
    private ExpertService expertService;

    /**
     * 分页展示所有问答
     *
     * @param pageNum  页码
     * @param pageSize 每页数量
     * @return 问答列表
     */
    @ApiOperation(value = "分页展示所有问答")
    @GetMapping("/all")
    public Result selectAllQuestions(@RequestParam("pageNum") Integer pageNum, @RequestParam(value = "pageSize", defaultValue = "6") Integer pageSize) {
        Page<Question> page = questionService.findPage(pageNum, pageSize);
        return Result.builder()
                .code(Code.QUERY_SUCCESS.getCode())
                .message(Code.QUERY_SUCCESS.getInfo())
                .data(page)
                .flag(Flag.SUCCESS.isCode()).build();
    }

    /**
     * 分页查询关键字问答
     *
     * @param pageNum  页码
     * @param pageSize 每页数量
     * @param keys     关键字
     * @return 问答页
     */
    @ApiOperation(value = "分页查询关键字问答")
    @GetMapping("/selectByKeys")
    public Result selectByKeys(@RequestParam("pageNum") Integer pageNum,
                               @RequestParam(value = "pageSize", defaultValue = "6") Integer pageSize,
                               @RequestParam("keys") String keys) {
        Page<Question> page = questionService.findPageByKeys(keys, pageNum, pageSize);
        return Result.builder()
                .code(Code.QUERY_SUCCESS.getCode())
                .message(Code.QUERY_SUCCESS.getInfo())
                .data(page)
                .flag(Flag.SUCCESS.isCode())
                .build();
    }

    /**
     * 根据id查询问答
     *
     * @param id 问答id
     * @return 问答
     */
    @ApiOperation(value = "根据id查询问答")
    @GetMapping("/selectQuestionById/{id}")
    public Result selectQuestionById(@PathVariable("id") String id) {
        Question knowledge = questionService.selectById(Integer.valueOf(id));
        return Result.builder()
                .code(Code.QUERY_SUCCESS.getCode())
                .message(Code.QUERY_SUCCESS.getInfo())
                .data(knowledge)
                .flag(Flag.SUCCESS.isCode())
                .build();
    }

    /**
     * 添加问答
     *
     * @param question 问答
     * @return 添加结果
     */
    @ApiOperation(value = "添加问答")
    @PostMapping("/addQuestion")
    public Result addQuestion(@RequestBody Question question, BindingResult bindingResult) {
        //检查
        if (null == question || bindingResult.hasErrors()) {
            StringBuffer stringBuffer = new StringBuffer();
            List<ObjectError> allErrors = bindingResult.getAllErrors();
            for (ObjectError objectError : allErrors) {
                stringBuffer.append(objectError.getDefaultMessage()).append("; ");
            }
            String s = stringBuffer.toString();
            log.info("发现错误：{}", s);
            return Result.builder()
                    .code(Code.ADD_FAIL.getCode())
                    .flag(Flag.FAIL.isCode())
                    .message(Code.ADD_FAIL.getInfo())
                    .build();
        }
        //获取登陆的用户名
        UserDetails principal = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String name = principal.getUsername();
        question.setQuestioner(name);
        System.out.println(question);
        boolean add = questionService.addQuestion(question);
        return Result.builder()
                .code(add ? Code.ADD_SUCCESS.getCode() : Code.ADD_FAIL.getCode())
                .message(add ? Code.ADD_SUCCESS.getInfo() : Code.ADD_FAIL.getInfo())
                .flag(add ? Flag.SUCCESS.isCode() : Flag.FAIL.isCode())
                .build();
    }


    /**
     * 根据id修改问答
     *
     * @param question 问答
     * @return 修改结果
     */
    @ApiOperation(value = "根据id修改问答")
    @PutMapping("/updateQuestionById")
    public Result updateQuestionById(@RequestBody Question question) {
        log.info("修改的问答：{}", question);
        if (null == question|| null == question.getId()) {
            return Result.builder()
                    .code(Code.UPDATE_FAIL.getCode())
                    .message(Code.UPDATE_FAIL.getInfo())
                    .flag(Flag.FAIL.isCode())
                    .build();
        }
        boolean update = questionService.updateById(question);
        return Result.builder()
                .flag(update ? Flag.SUCCESS.isCode() : Flag.FAIL.isCode())
                .code(update ? Code.UPDATE_SUCCESS.getCode() : Code.UPDATE_FAIL.getCode())
                .message(update ? Code.UPDATE_SUCCESS.getInfo() : Code.UPDATE_FAIL.getInfo()).build();
    }

    /**
     * 根据id删除问答
     *
     * @param id 问答id
     * @return 删除结果
     */
    @ApiOperation(value = "根据id删除问答")
    @DeleteMapping("/deleteQuestionById/{id}")
    public Result deleteQuestionById(@PathVariable("id") String id) {
        boolean delete = questionService.deleteById(Integer.valueOf(id));
        return Result.builder()
                .flag(delete ? Flag.SUCCESS.isCode() : Flag.FAIL.isCode())
                .code(delete ? Code.DELETE_SUCCESS.getCode() : Code.DELETE_FAIL.getCode())
                .message(delete ? Code.DELETE_SUCCESS.getInfo() : Code.DELETE_FAIL.getInfo()).build();
    }

    /**
     * 根据用户类型查询问答
     *
     * @param kind 用户类型
     * @return 问答列表
     */
    @ApiOperation(value = "根据用户名类型查询问答")
    @GetMapping("/selectQuestionByKind/{kind}")
    public Result selectQuestionByKind(@PathVariable("kind") String kind) {
        List<Question> questions = questionService.selectQuestionByKind(kind);
        return Result.builder()
                .code(Code.QUERY_SUCCESS.getCode())
                .message(Code.QUERY_SUCCESS.getInfo())
                .data(questions)
                .flag(Flag.SUCCESS.isCode())
                .build();
    }


    /**
     * 分页展示所有专家
     *
     * @param pageNum  页码
     * @param pageSize 每页数量
     * @return 专家列表
     */
    @ApiOperation(value = "分页展示所有专家")
    @GetMapping("/allExperts")
    public Result selectExperts(@RequestParam("pageNum") Integer pageNum, @RequestParam(value = "pageSize", defaultValue = "6") Integer pageSize) {
        Page<Expert> page = expertService.findPage(pageNum, pageSize);
        return Result.builder()
                .code(Code.QUERY_SUCCESS.getCode())
                .message(Code.QUERY_SUCCESS.getInfo())
                .data(page)
                .flag(Flag.SUCCESS.isCode()).build();
    }

    /**
     * 分页查询关键字专家
     *
     * @param pageNum  页码
     * @param pageSize 每页数量
     * @param keys     关键字
     * @return 问答页
     */
    @ApiOperation(value = "分页查询关键字专家")
    @GetMapping("/selectExpertByKeys")
    public Result selectExpertByKeys(@RequestParam("pageNum") Integer pageNum,
                                     @RequestParam(value = "pageSize", defaultValue = "6") Integer pageSize,
                                     @RequestParam("keys") String keys) {
        Page<Expert> page = expertService.findPageByKeys(keys, pageNum, pageSize);
        return Result.builder()
                .code(Code.QUERY_SUCCESS.getCode())
                .message(Code.QUERY_SUCCESS.getInfo())
                .data(page)
                .flag(Flag.SUCCESS.isCode())
                .build();
    }
}
